import 'dart:async';
import 'dart:io';

import 'package:bike_ride/common/util/hysize_fit.dart';
import 'package:bike_ride/common/util/permission_utils.dart';
import 'package:bike_ride/model/version/model/version_info.dart';
import 'package:bike_ride/model/version/version_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:simple_html_css/simple_html_css.dart';


///应用更新弹窗
class UpgradeDialog extends StatefulWidget {
  const UpgradeDialog({
    Key? key,
    required this.feedBack,
    required this.forceUpdate,
    required this.showTipDialog,
    required this.versionModel,
    required this.valueChanged,
    required this.hasCancel,
  }) : super(key: key);
  final bool feedBack;
  final bool forceUpdate;
  final Function showTipDialog;
  final VersionInfo versionModel;
  final ValueChanged valueChanged;
  final bool hasCancel;

  @override
  State<StatefulWidget> createState() {
    return _UpgradeDialogState();
  }
}

class _UpgradeDialogState extends State<UpgradeDialog> {
  static const RoundedRectangleBorder _defaultDialogShape =
  RoundedRectangleBorder(
      borderRadius: BorderRadius.all(Radius.circular(4.0)));

  late VersionInfo versionModel;

  int progress = 0;
  bool isDownload = false;

  late OnDownloadProgress progressCallback;
  @override
  void initState() {
    super.initState();
    versionModel = widget.versionModel;
    progressCallback = (int count, int total) {
      progress = ((count / total) * 100).toInt();

      setState(() {});
      if (progress == 100) {
        Navigator.pop(context);
      }
    };

    VersionUtil().addListener(progressCallback);
    VersionUtil().isBackgroundDownload = false;
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      if(versionModel.upgradeType==3){
        Navigator.pop(context);
        VersionUtil().isBackgroundDownload = true;
        //从设置-版本号进入
        if(Platform.isAndroid&&widget.feedBack){
          widget.showTipDialog();
        }
        _startDownload();
      }else if(widget.forceUpdate){
        _startDownload();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    VersionUtil().removeListener(progressCallback);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: MediaQuery.removeViewInsets(
          removeLeft: true,
          removeTop: true,
          removeRight: true,
          removeBottom: true,
          context: context,
          child: Center(
            child: ConstrainedBox(
              constraints: BoxConstraints(minWidth: 620.rpx, maxWidth: 630.rpx),
              child: Material(
                color: Colors.white,
                //elevation: _defaultElevation,
                shape: _defaultDialogShape,
                type: MaterialType.card,
                child:Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: <Widget>[
                    Stack(
                      children: <Widget>[
                        Container(
                          width: double.infinity,
                          height: 160.rpx,
                          decoration: BoxDecoration(borderRadius: BorderRadius.only(topLeft:Radius.circular(10.rpx),topRight: Radius.circular(10.rpx)),
                              color: Theme.of(context).colorScheme.primary.withOpacity(0.8)),
                        ),
                        Padding(
                          padding: EdgeInsets.all(30.rpx),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Text(
                                isDownload?'资源加载中...':'发现新版本',
                                style: TextStyle(
                                    fontSize: 48.rpx, color: Colors.white),
                              ),
                              Text(
                                versionModel.version.toString(),
                                style: TextStyle(
                                    fontSize: 44.rpx, color: Colors.white),
                              ),
                            ],
                          ),
                        )
                      ],
                    ),

                    ...getColumnWidget(),
                  ],
                ),
              ),
            ),
          )),
      onWillPop: ()async{
        if(widget.hasCancel){
          if(Platform.isAndroid && progress>0){
            Future.delayed(const Duration(milliseconds: 200),(){
              widget.showTipDialog();
            });
          }
          return true;
        }
        return false;
      },
    );
  }


  List<Widget> getColumnWidget(){
    if(isDownload){
      return [Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Offstage(
            offstage: progress >= 0,
            child: const Text(
              '网络异常，请重试!',
              textAlign: TextAlign.center,
              style: TextStyle(
                  fontSize: 14, color: Colors.redAccent),
            ),
          ),
          SizedBox(height: 16.rpx,),
          Offstage(
            offstage: progress < 0,
            child: RichText(
              textAlign: TextAlign.center,
              text: TextSpan(children: <TextSpan>[
                const TextSpan(
                    style: TextStyle(
                        fontSize: 14, color: Color(0xFF666666)),
                    text: '下载进度 '),
                TextSpan(
                    style: const TextStyle(
                        fontSize: 14, color: Colors.blueAccent),
                    text: "$progress%")
              ]),
            ),
          ),
          SizedBox(height: 16.rpx,),
          Container(
            padding: const EdgeInsets.only(left: 24, right: 24),
            height: 4,
            child: const LinearProgressIndicator(
              backgroundColor: Color(0xffe5e5e5),
            ),
          ),

          SizedBox(height: 16.rpx,),

          const Divider(),
          SizedBox(
            height: 100.rpx,
            width: double.infinity,
            child: TextButton(
                onPressed: () async{
                  await PermissionUtil().handleNotificationPermission().then((value){
                    if (progress >= 0) {
                      if(widget.hasCancel){
                        Navigator.pop(context);
                        widget.showTipDialog();
                        VersionUtil().isBackgroundDownload = true;
                      }else{
                        EasyLoading.showToast('资源正快马加鞭的准备中..已下载$progress%',toastPosition: EasyLoadingToastPosition.bottom);
                      }
                    } else {
                      EasyLoading.showToast('已重新请求网络');
                      VersionUtil().downloadApk(
                        versionModel.remoteUrl!,
                        widget.valueChanged,
                        widget.forceUpdate,
                      );
                    }
                  });
                },
                child: Text(
                  progress >= 0 ? (widget.hasCancel?'后台下载':'下载中') : '重试',
                  style: TextStyle(fontSize: 32.rpx,color: Colors.grey),
                )),
          ),
        ],
      )];
    }else{
      return [
        Padding(
            padding: EdgeInsets.only(left: 36.rpx,top: 6.rpx),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                if(versionModel.title!=null)
                  Text(
                    versionModel.title.toString(),
                    style: TextStyle(fontSize: 28.rpx,color: Colors.grey),
                  ),
                HTML.toRichText(context, versionModel.desc??'')
              ],
            )
        ),
        const Divider(),
        Row(
          children: <Widget>[
            if(widget.hasCancel)
            Expanded(
                child: Container(
                  decoration: const BoxDecoration(
                      border: Border(right:BorderSide(width: 0.2, color: Colors.grey))
                  ),
                  child: TextButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      child: Text(
                        '暂不更新',
                        style: TextStyle(fontSize: 32.rpx,color: Colors.grey),
                      )),
                )),
            Expanded(
                child: TextButton(
                    onPressed: () =>_startDownload(),
                    child: Text(
                      '去更新',
                      style: TextStyle(fontSize: 32.rpx,color: Colors.grey),
                    ))),
          ],
        ),
      ];
    }
  }

  ///下载
  _startDownload(){
    if(Platform.isAndroid){
      VersionUtil().downloadApk(
        versionModel.remoteUrl!,
        widget.valueChanged,
        widget.forceUpdate,
      );
      setState(() {
        isDownload = true;
      });
    }else{
      //ios直接返回下载地址，前往苹果指定appStore下载
      widget.valueChanged(versionModel.remoteUrl);
    }
  }

}
